package com.web.listener;

import java.util.HashSet;
import java.util.Set;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

//监听在线用户
@WebListener
public class OnlineUserListener implements 
	HttpSessionListener,HttpSessionAttributeListener,	ServletContextListener{
	private  ServletContext application;
	@Override
	public void contextInitialized(ServletContextEvent event) {
		application = event.getServletContext();
		Set<String> onlineSet  = new HashSet<String>();
		application.setAttribute("user", onlineSet);
	}

	@Override
	public void sessionDestroyed(HttpSessionEvent event) {
		//session销毁 在线用户减一 
		HttpSession  session= event.getSession();
		//销毁的用户名
		String name = (String) session.getAttribute("name");
		Set<String> onlineSet = (Set<String>)application.getAttribute("user");
		onlineSet.remove(name);
	}

	@Override
	public void attributeAdded(HttpSessionBindingEvent event) {
		//登录新用户--- 在线用户加一
		String value = event.getValue().toString();
		Set<String> onlineSet = (Set<String>)application.getAttribute("user");
		onlineSet.add(value);
	}

	@Override
	public void attributeRemoved(HttpSessionBindingEvent event) {
		//如果安全退出调用session.removeAttribute("user");
	}

	@Override
	public void attributeReplaced(HttpSessionBindingEvent arg0) {
	}
	@Override
	public void sessionCreated(HttpSessionEvent arg0) {
		
	}

	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		// 服务器停止所有的数据都无效
		
	}

	
	
}
